########################################################################
# PLS 206 — Week 8 live coding, part 2: hierarchical clustering
# Grey Monroe, Fall 2026
########################################################################

# install.packages(c("ggplot2", "patchwork", "maps"))
library(ggplot2)
library(patchwork)

########################################################################
# Helpers (run this block once)
########################################################################

# Draw a dendrogram with ggplot. k = number of clusters to colour; labels = leaf labels (NULL for none).
plot_tree <- function(hc, k = NULL, labels = if (is.null(hc$labels)) seq_along(hc$order) else hc$labels, title = NULL) {
  n <- length(hc$order); xpos <- numeric(n); xpos[hc$order] <- 1:n
  cl <- if (is.null(k)) rep(1, n) else cutree(hc, k)
  cx <- numeric(n - 1); memb <- vector("list", n - 1); segs <- NULL
  node <- function(j) if (j < 0) list(x = xpos[-j], y = 0, m = -j) else list(x = cx[j], y = hc$height[j], m = memb[[j]])
  pure <- function(m) { u <- unique(cl[m]); if (length(u) == 1 && !is.null(k)) as.character(u) else "tree" }
  for (i in 1:(n - 1)) {
    a <- node(hc$merge[i, 1]); b <- node(hc$merge[i, 2]); h <- hc$height[i]
    cx[i] <- (a$x + b$x) / 2; memb[[i]] <- c(a$m, b$m)
    segs <- rbind(segs, data.frame(x = c(a$x, b$x, a$x), y = c(a$y, b$y, h), xend = c(a$x, b$x, b$x), yend = h,
                                   col = c(pure(a$m), pure(b$m), pure(memb[[i]]))))
  }
  p <- ggplot(segs) + geom_segment(aes(x, y, xend = xend, yend = yend, colour = col)) +
    scale_colour_manual(values = c(tree = "black", setNames(scales::hue_pal()(max(cl)), 1:max(cl))), guide = "none") +
    labs(x = NULL, y = "height (distance at merge)", title = title) + theme_classic() +
    theme(axis.line.x = element_blank(), axis.text.x = element_blank(), axis.ticks.x = element_blank())
  if (!is.null(labels)) p <- p + annotate("text", x = xpos, y = -0.03 * max(hc$height), label = labels, vjust = 1)
  p
}

# Heatmap with rows (genes) and columns (tissues) ordered by their own trees, both trees drawn.
# Each row is scaled to mean 0, SD 1, so the colour shows where that gene is high or low.
heatmap_tree <- function(m, hc_rows, hc_cols) {
  z <- t(scale(t(m)))
  d <- data.frame(row = rep(1:nrow(m), ncol(m)), col = rep(1:ncol(m), each = nrow(m)),
                  z = pmax(pmin(as.vector(z[hc_rows$order, hc_cols$order]), 3), -3))
  heat <- ggplot(d, aes(col, row, fill = z)) + geom_raster() +
    scale_fill_gradient2(low = "blue", mid = "white", high = "red") +
    scale_x_continuous(breaks = 1:ncol(m), labels = colnames(m)[hc_cols$order], expand = c(0, 0)) +
    scale_y_continuous(expand = c(0, 0)) + labs(x = NULL, y = NULL) + theme_classic() +
    theme(axis.text.y = element_blank(), axis.ticks.y = element_blank(), axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5, size = 6))
  top <- plot_tree(hc_cols, labels = NULL) + theme_void() + scale_x_continuous(expand = c(0, 0)) +
    coord_cartesian(xlim = c(0.5, ncol(m) + 0.5))
  side <- plot_tree(hc_rows, labels = NULL) + theme_void() + scale_x_continuous(expand = c(0, 0)) +
    coord_flip(xlim = c(0.5, nrow(m) + 0.5)) + scale_y_reverse()
  plot_spacer() + top + side + heat + plot_layout(ncol = 2, widths = c(1, 5), heights = c(1, 4), guides = "collect")
}

# A world map with points coloured by cluster
map_clusters <- function(lon, lat, cluster) {
  ggplot() + geom_polygon(data = map_data("world"), aes(long, lat, group = group), fill = "grey92", colour = "grey75") +
    geom_point(aes(lon, lat, colour = factor(cluster)), size = 2.5) +
    coord_quickmap(xlim = c(-125, 80), ylim = c(28, 68)) + labs(colour = "cluster", x = NULL, y = NULL) + theme_classic()
}

# Simulated points: two round blobs joined by a thin bridge, plus an arc on top
make_blobs <- function() {
  set.seed(8)
  t3 <- seq(0, 1, length.out = 16)
  rbind(data.frame(x = rnorm(18, 0, 0.35), y = rnorm(18, 0, 0.35)),
        data.frame(x = rnorm(18, 3.2, 0.35), y = rnorm(18, 0.2, 0.35)),
        data.frame(x = 0.2 + 3 * t3 + rnorm(16, 0, 0.08), y = 2.6 + 0.6 * sin(pi * t3) + rnorm(16, 0, 0.08)),
        data.frame(x = seq(0.6, 2.6, length.out = 6), y = rnorm(6, 0.1, 0.06)))
}

########################################################################
# 1. Build a tree: 8 points
########################################################################

toy <- data.frame(x = c(1, 1.45, 4, 4.7, 4.3, 2.1, 2.9, 6.0),
                  y = c(1.2, 1.5, 1.1, 1.0, 1.9, 4.1, 4.5, 3.0))

ggplot(toy, aes(x, y, label = 1:8)) + geom_label(size = 5) + theme_classic()

# step 1: the distance between every pair of points (Euclidean by default)
d <- dist(toy)
round(d, 2)                 # smallest: points 1 and 2, 0.54 -> they merge first

# step 2: merge the closest two, repeat
hc <- hclust(d)             # method = "complete" is the default
round(hc$height, 2)         # merge heights: 0.54 0.71 0.89 0.98 2.76 3.81 5.31
plot_tree(hc)               # same as plot(hc)

# step 3: cut the tree into k clusters
cutree(hc, k = 3)           # 1 1 2 2 2 3 3 2: {1,2}, {3,4,5,8}, {6,7}
toy$cluster <- factor(cutree(hc, k = 3))
plot_tree(hc, k = 3)
ggplot(toy, aes(x, y, label = 1:8, colour = cluster)) + geom_label(size = 5) + theme_classic()

########################################################################
# 2. Linkage: how far apart are two clusters?
########################################################################

# five points on a line
x1 <- c(0.6, 0, -0.25, 1.05, -1)
names(x1) <- 1:5
d1 <- dist(x1)
d1

hc_complete <- hclust(d1, method = "complete")   # farthest pair
hc_single   <- hclust(d1, method = "single")     # closest pair
hc_complete$height          # 0.25 0.45 1.00 2.05: point 5 joins {2,3} at 1.00
hc_single$height            # 0.25 0.45 0.60 0.75: {2,3} joins {1,4} at 0.60, point 5 last
plot_tree(hc_complete, title = "complete") + plot_tree(hc_single, title = "single")

# same 58 points, four linkages, each cut at k = 3
blobs <- make_blobs()
d_blobs <- dist(blobs)
for (m in c("single", "complete", "average", "ward.D2")) {
  print(sort(table(cutree(hclust(d_blobs, method = m), k = 3)), decreasing = TRUE))
}
# cluster sizes: single 41-16-1 (one stray point is a cluster), complete 23-19-16, average 21-21-16, ward.D2 21-21-16

blobs$single <- factor(cutree(hclust(d_blobs, method = "single"), k = 3))
blobs$ward   <- factor(cutree(hclust(d_blobs, method = "ward.D2"), k = 3))
ggplot(blobs, aes(x, y, colour = single)) + geom_point(size = 2) + theme_classic() + labs(title = "single") +
  ggplot(blobs, aes(x, y, colour = ward)) + geom_point(size = 2) + theme_classic() + labs(title = "ward.D2")

########################################################################
# 3. Distance
########################################################################

two <- data.frame(x = c(1, 4), y = c(1, 3))
dist(two)                        # Euclidean: 3.61
dist(two, method = "manhattan")  # Manhattan: 3 + 2 = 5

# Scale first: Colombia climate, temperature (°C) and rainfall (mm)
colombia <- read.csv("https://greymonroe.github.io/PLS_206/data/colombia_climate.csv")
sd(colombia$bio1)                # 4.3 °C
sd(colombia$bio12)               # 931 mm: unscaled, rainfall decides every distance

colombia$unscaled <- factor(cutree(hclust(dist(colombia[, c("bio1", "bio12")]), "ward.D2"), k = 3))
colombia$scaled   <- factor(cutree(hclust(dist(scale(colombia[, c("bio1", "bio12")])), "ward.D2"), k = 3))
ggplot(colombia, aes(bio1, bio12, colour = unscaled)) + geom_point(size = 0.6) + theme_classic() +
  labs(x = "mean temperature (°C)", y = "annual rainfall (mm)", title = "not scaled: bands of rainfall") +
  ggplot(colombia, aes(bio1, bio12, colour = scaled)) + geom_point(size = 0.6) + theme_classic() +
  labs(x = "mean temperature (°C)", y = "annual rainfall (mm)", title = "scaled")

########################################################################
# 4. Arabidopsis thaliana: 150 plants, 10,933 genetic markers (1 = carries the variant)
########################################################################

plants <- read.csv("https://greymonroe.github.io/PLS_206/data/a_thaliana_150_snps.csv")
plants[1:5, 1:8]
snps <- plants[, -(1:5)]         # columns 1-5: Name, Country, Region, Lat, Long

# binary (Jaccard) distance: differences / markers where either plant has a 1
d_plants <- dist(snps, method = "binary")
median(d_plants)                 # 0.66: most pairs of plants about equally different

# complete linkage: one big cluster and a few stragglers
hc_plants <- hclust(d_plants, method = "complete")
table(cutree(hc_plants, k = 5))  # 144 plants in one cluster
plot_tree(hc_plants, k = 5, labels = NULL)

# Ward.D2: clusters that follow geography
hc_ward <- hclust(d_plants, method = "ward.D2")
plot_tree(hc_ward, k = 5, labels = NULL)
plants$cluster <- cutree(hc_ward, k = 5)
table(plants$cluster, plants$Country)
# one cluster per row: 39 of 40 Swedish plants together, all 8 Russian plants with Central Asia,
# 12 of 15 USA plants on their own, 5 of 9 Italian plants, and the rest of Europe
map_clusters(plants$Long, plants$Lat, plants$cluster)

########################################################################
# 5. Gene expression: 1000 genes x 53 Arabidopsis tissues
########################################################################

expression <- read.csv("https://greymonroe.github.io/PLS_206/data/gene_expression.csv", check.names = FALSE)
dim(expression)                  # 1000 genes, 53 tissues

# cluster the tissues on the shape of their expression profiles: 1 - correlation
d_tissues <- as.dist(1 - cor(expression))
hc_tissues <- hclust(d_tissues, method = "average")
plot_tree(hc_tissues, labels = NULL) +
  annotate("text", x = 1:53, y = -0.02, label = colnames(expression)[hc_tissues$order], angle = 90, hjust = 1, size = 2.5) +
  coord_cartesian(ylim = c(-0.8, 0.65))
# the five root and culture samples form one branch; seeds and embryos sit together

# cluster the genes the same way: genes that rise and fall together across tissues
d_genes <- as.dist(1 - cor(t(expression)))
hc_genes <- hclust(d_genes, method = "average")

# heatmap with both trees: genes down the side, tissues across the top
heatmap_tree(as.matrix(expression), hc_genes, hc_tissues)
# blocks of red: a set of genes switched on together in a set of tissues

########################################################################
# 6. k-means vs hierarchical: Colombia, all 19 climate variables
########################################################################

clim <- scale(colombia[, paste0("bio", 1:19)])

set.seed(1)
km <- kmeans(clim, centers = 4, nstart = 25)
hc_clim <- hclust(dist(clim), method = "ward.D2")

colombia$kmeans <- factor(km$cluster)
colombia$hclust <- factor(cutree(hc_clim, k = 4))
table(colombia$hclust, colombia$kmeans)
# each hclust cluster lines up with one k-means cluster: 402, 1397, 1150 and 162 cells,
# so 3111 of 3571 cells (87%) agree

ggplot(colombia, aes(lon, lat, fill = kmeans)) + geom_tile() + coord_fixed() + theme_void() + labs(title = "kmeans") +
  ggplot(colombia, aes(lon, lat, fill = hclust)) + geom_tile() + coord_fixed() + theme_void() + labs(title = "hclust, Ward.D2")
